<template>
  <div class="finance-statistics">
    <el-row :gutter="20">
      <!-- 统计卡片 -->
      <el-col :span="24">
        <div class="stat-cards">
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <el-icon><House /></el-icon>
                <span>总出租房源数</span>
              </div>
            </template>
            <div class="stat-value">{{ statistics.totalRentedHouses }}</div>
          </el-card>
          
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <el-icon><Money /></el-icon>
                <span>总收入(元)</span>
              </div>
            </template>
            <div class="stat-value">{{ statistics.totalIncome.toLocaleString() }}</div>
          </el-card>
          
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <el-icon><User /></el-icon>
                <span>总用户数</span>
              </div>
            </template>
            <div class="stat-value">{{ statistics.totalUsers }}</div>
          </el-card>
          
          <el-card class="stat-card">
            <template #header>
              <div class="card-header">
                <el-icon><HomeFilled /></el-icon>
                <span>总房源数</span>
              </div>
            </template>
            <div class="stat-value">{{ statistics.totalHouses }}</div>
          </el-card>
        </div>
      </el-col>
      
      <!-- 收入趋势图 -->
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>月度收入趋势</span>
              <el-select v-model="yearFilter" placeholder="选择年份" style="width: 120px">
                <el-option v-for="year in availableYears" :key="year" :label="year + '年'" :value="year" />
              </el-select>
            </div>
          </template>
          <div class="chart-container" ref="incomeChartContainer"></div>
        </el-card>
      </el-col>
      
      <!-- 房源类型分布 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>房源类型分布</span>
            </div>
          </template>
          <div class="chart-container" ref="houseTypeChartContainer"></div>
        </el-card>
      </el-col>
      
      <!-- 收入明细表格 -->
      <el-col :span="24">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>收入明细</span>
              <div>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  @change="handleDateRangeChange"
                />
                />
                <el-button type="primary" size="small" style="margin-left: 10px" @click="exportReport">导出报表</el-button>
              </div>
            </div>
          </template>
          
          <el-table :data="incomeRecords" style="width: 100%" border stripe v-loading="loading">
            <el-table-column prop="rent_id" label="订单ID" width="100" />
            <el-table-column prop="house_name" label="房源名称" min-width="150" />
            <el-table-column label="租期" width="200">
              <template #default="scope">
                <span>{{ formatDate(scope.row.start_date) }} 至 {{ formatDate(scope.row.end_date) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="tenant_name" label="租客" width="100" />
            <el-table-column prop="landlord_name" label="房东" width="100" />
            <el-table-column prop="amount" label="金额(元)" width="120">
              <template #default="scope">
                <span>{{ scope.row.amount.toLocaleString() }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="rent_date" label="支付时间" width="180">
              <template #default="scope">
                <span>{{ formatDateTime(scope.row.rent_date) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pay_type" label="支付方式" width="120" />
          </el-table>
          
          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { House, Money, User, HomeFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import * as echarts from 'echarts'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const yearFilter = ref(new Date().getFullYear())
const availableYears = [2025, 2024, 2023, 2022, 2021]
const dateRange = ref([])

// 图表容器引用
const incomeChartContainer = ref(null)
const houseTypeChartContainer = ref(null)

// 图表实例
let incomeChart = null
let houseTypeChart = null

// 统计数据
const statistics = reactive({
  totalRentedHouses: 0,
  totalIncome: 0,
  totalUsers: 0,
  totalHouses: 0
})

// 收入记录
const incomeRecords = ref([])

// 日期格式化函数
const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 日期时间格式化函数
const formatDateTime = (dateString) => {
  if (!dateString) return '未设置'
  const date = new Date(dateString)
  return `${formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
}

// 获取租赁统计数据
const fetchRentStatistics = async () => {
  try {
    const response = await axios.get('http://127.0.0.1:5000/api/rent/statistics', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.data.status === 200) {
      return response.data.data
    } else {
      ElMessage.error(response.data.msg || '获取租赁统计数据失败')
      return []
    }
  } catch (error) {
    console.error('获取租赁统计数据失败:', error)
    ElMessage.error('获取租赁统计数据失败，请稍后重试')
    return []
  }
}

// 初始化收入趋势图
const initIncomeChart = async () => {
  if (incomeChart) {
    incomeChart.dispose()
  }
  
  const chartDom = incomeChartContainer.value
  incomeChart = echarts.init(chartDom)
  
  // 从API获取租赁统计数据
  const statisticsData = await fetchRentStatistics()
  
  // 过滤当前选择年份的数据
  const currentYearData = statisticsData.filter(item => item.year === yearFilter.value)
   
   // 处理数据格式，按月份排序
   const monthlyData = [];
   for (let i = 1; i <= 12; i++) {
     // 查找当前月份的数据
     const monthData = currentYearData.find(item => item.month === i);
     
     // 如果找到数据则使用实际数据，否则使用默认值0
     monthlyData.push({
       month: i + '月',
       income: monthData ? monthData.total_amount : 0,
       count: monthData ? monthData.count : 0
     });
   }
   
   // 设置图表选项
   const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['收入金额', '出租数量']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: monthlyData.map(item => item.month)
      }
    ],
    yAxis: [
      {
        type: 'value',
        name: '收入金额(元)',
        axisLabel: {
          formatter: '{value}'
        }
      },
      {
        type: 'value',
        name: '出租数量',
        axisLabel: {
          formatter: '{value}'
        }
      }
    ],
    series: [
      {
        name: '收入金额',
        type: 'bar',
        data: monthlyData.map(item => item.income),
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '出租数量',
        type: 'line',
        yAxisIndex: 1,
        data: monthlyData.map(item => item.count),
        itemStyle: {
          color: '#67C23A'
        },
        lineStyle: {
          width: 3
        },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }
  
  incomeChart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    incomeChart.resize()
  })
}

// 获取财务统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://127.0.0.1:5000/api/admin/statistics', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.status === 200) {
      const data = response.data
      statistics.totalRentedHouses = data.total_rented
      statistics.totalIncome = data.total_income
      statistics.totalUsers = data.normal_users_count
      statistics.totalHouses = data.total_houses
    } else {
      ElMessage.error('获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取收入记录
const fetchIncomeRecords = async () => {
  loading.value = true
  try {
    // 构建请求参数
    let params = {
      page: currentPage.value,
      pageSize: pageSize.value
    }
    
    // 只有当日期范围有值时才添加到请求参数中
    if (dateRange.value && dateRange.value.length === 2) {
      // 确保日期格式正确，使用字符串而非响应式对象
      const startDate = typeof dateRange.value[0] === 'string' ? dateRange.value[0] : formatDate(dateRange.value[0])
      const endDate = typeof dateRange.value[1] === 'string' ? dateRange.value[1] : formatDate(dateRange.value[1])
      
      params.startDate = startDate
      params.endDate = endDate
      console.log('筛选日期范围:', params.startDate, '至', params.endDate)
    }
    
    // 调用后端API获取租赁详细信息列表
    const response = await axios.get('http://127.0.0.1:5000/api/rent/rentList', {
      params,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    // 打印完整的响应数据，用于调试
    // console.log('API响应数据:', response.data)
    
    if (response.data.status === 200) {
      // 处理返回的数据
      const responseData = response.data.data || []
      // console.log('处理前的数据:', responseData)
      
      incomeRecords.value = responseData.map(item => ({
        ...item,
        amount: parseFloat(item.amount) // 确保金额是数字类型
      }))
      // console.log('处理后的数据:', incomeRecords.value)
      
      total.value = responseData.length
    } else {
      ElMessage.error(response.data.msg || '获取租赁详细信息失败')
    }
  } catch (error) {
    console.error('获取租赁详细信息失败:', error)
    ElMessage.error('获取租赁详细信息失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理日期范围变化
const handleDateRangeChange = () => {
  console.log('日期范围变化:', dateRange.value)
  // 重置页码并获取数据
  currentPage.value = 1
  // 延迟执行，确保日期值已更新
  setTimeout(() => {
    fetchIncomeRecords()
  }, 100)
}

// 导出报表功能
const exportReport = () => {
  if (incomeRecords.value.length === 0) {
    ElMessage.warning('没有数据可供导出')
    return
  }
  
  try {
    // 创建CSV内容
    let csvContent = '订单ID,房源名称,租期开始,租期结束,租客,房东,金额(元),支付时间,支付方式\n'
    
    incomeRecords.value.forEach(record => {
      const row = [
        record.rent_id,
        record.house_name,
        formatDate(record.start_date),
        formatDate(record.end_date),
        record.tenant_name,
        record.landlord_name,
        record.amount,
        formatDateTime(record.rent_date),
        record.pay_type
      ]
      
      // 处理CSV中的特殊字符
      const processedRow = row.map(cell => {
        if (cell === null || cell === undefined) return ''
        const cellStr = String(cell)
        // 如果包含逗号、双引号或换行符，则用双引号包裹并将内部双引号转义
        if (cellStr.includes(',') || cellStr.includes('"') || cellStr.includes('\n') || cellStr.includes('\r')) {
          return `"${cellStr.replace(/"/g, '""')}"`
        }
        return cellStr
      })
      
      // 确保使用Windows换行符CRLF
      csvContent += processedRow.join(',') + '\r\n'
    })
    
    // 添加BOM头解决中文乱码问题
    const BOM = new Uint8Array([0xEF, 0xBB, 0xBF])
    const csvContentWithBOM = new Blob([BOM, csvContent], { type: 'text/csv;charset=utf-8;' })
    
    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(csvContentWithBOM)
    
    // 设置下载属性
    const date = new Date()
    const dateStr = `${date.getFullYear()}${String(date.getMonth() + 1).padStart(2, '0')}${String(date.getDate()).padStart(2, '0')}`
    link.setAttribute('href', url)
    link.setAttribute('download', `租赁收入明细_${dateStr}.csv`)
    link.style.visibility = 'hidden'
    
    // 添加到文档并触发点击
    document.body.appendChild(link)
    link.click()
    
    // 清理
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    ElMessage.success('报表导出成功')
  } catch (error) {
    console.error('导出报表失败:', error)
    ElMessage.error('导出报表失败，请稍后重试')
  }
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchIncomeRecords()
}

// 处理每页显示数量变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchIncomeRecords()
}

// 初始化房源类型分布图
const initHouseTypeChart = async () => {
  if (houseTypeChart) {
    houseTypeChart.dispose()
  }
  
  try {
    const response = await axios.get('http://127.0.0.1:5000/api/admin/statistics', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (response.status === 200) {
      const data = response.data.house_types
      const houseTypeData = [
        { value: data.one_room, name: '一室' },
        { value: data.two_room, name: '二室' },
        { value: data.three_room, name: '三室' },
        { value: data.four_room, name: '四室' }
      ]
      
      const chartDom = houseTypeChartContainer.value
      houseTypeChart = echarts.init(chartDom)
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: houseTypeData.map(item => item.name)
        },
        series: [
          {
            name: '房源类型',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: houseTypeData
          }
        ]
      }
      
      houseTypeChart.setOption(option)
    } else {
      ElMessage.error('获取房源类型数据失败')
    }
  } catch (error) {
    console.error('获取房源类型数据失败:', error)
    ElMessage.error('获取房源类型数据失败，请稍后重试')
  }
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    houseTypeChart && houseTypeChart.resize()
  })
}

// 监听年份筛选变化，重新加载收入趋势图
watch(yearFilter, () => {
  initIncomeChart()
})

onMounted(async () => {
  await fetchStatistics()
  await fetchIncomeRecords()
  
  // 初始化图表
  nextTick(() => {
    initIncomeChart()
    initHouseTypeChart()
  })
})
</script>

<style scoped>
.finance-statistics {
  width: 100%;
}

.stat-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  flex: 1;
  text-align: center;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header .el-icon {
  margin-right: 5px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  padding: 20px 0;
}

.chart-card {
  margin-bottom: 20px;
  height: 400px;
}

.chart-container {
  height: 320px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>